package com.network.server;

import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Component
public class ServerService {

    public static List<Socket> onlineSockets = new ArrayList<Socket>();

    /**
     * @throws IOException
     * @PostConstruct 依赖注入完成之后被自动调用
     */
    @PostConstruct
    public void startServer() throws IOException {
        System.out.println("-----------服务端---------------");
        // 创建服务器的socket监听8888
        ServerSocket serverSocket = new ServerSocket(8888);

        // 创建一个新的线程接收每次的socket连接请求避免阻塞方法冲突
        new Thread(() ->
        {
            try {
                while (true) {
                    Socket socket = null;
                    try {
                       // 接收连接
                        socket = serverSocket.accept();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    //获取ip地址
                    InetAddress remoteAddress = socket.getInetAddress();
                    String remoteIp = remoteAddress.getHostAddress();
                    //获取端口号
                    int remotePort = socket.getPort();

                    // 记录一个已连接的socket
                    onlineSockets.add(socket);
                    //获取一个socket就创建一个子线程
                    System.out.println(remoteIp + " :上线了" + remotePort+" "+ LocalDateTime.now());

                    // 新线程持续获取客户端消息
                    new ServerReaderThread(socket).start();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }


}
